package com.parenting.controller;


import com.parenting.config.TencentCosConfig;
import com.parenting.properties.TencentCosProperties4Picture;
import com.parenting.util.base.Result;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Api(tags = "文件管理接口", description = "文件管理接口，上传或删除图片文件")
@RequestMapping("/file")
@RestController
@Slf4j
public class UploadFileController {

    @Resource
    private TencentCosProperties4Picture tencentCosProperties4Picture;

    @Resource
    private TencentCosConfig tencentCosConfig;


    @PostMapping("upload")
    @ApiImplicitParam(name = "file", value = "文件", required = true)
    @ApiOperation("上传文件到腾讯云的cos中并返回url支持 图片、视频")
    public Result getUploadFile2TencentCosUrl(@RequestParam("file")  MultipartFile multipartFile) throws Exception {

        log.info("getUploadFile2TencentCosUrl fucntion of FileController start !");

        File localFile = null;
        String originalFilename = multipartFile.getOriginalFilename();
        try {
            originalFilename.substring(originalFilename.indexOf("."));
            log.info(" originalFilename.substring(originalFilename.indexO {}",  originalFilename.substring(originalFilename.indexOf(".")));
            log.info("fileName = {}",originalFilename.indexOf("."));
            String[] filename = originalFilename.split("\\.");


            localFile= File.createTempFile(filename[0]+ UUID.randomUUID(), filename[1]);
            multipartFile.transferTo(localFile);
            localFile.deleteOnExit();
        } catch (IOException e) {
            log.info("MultipartFile transto file IOException ={}",e.getMessage());
           // throw new HuihuaException(ResultCode.SYSTEM_ERROR.getCode(),ResultCode.SYSTEM_ERROR.getMsg());
        }

        if(localFile == null){
          //  throw new HuihuaException(ResultCode.MULTIPART_FILE_EOORO.getCode(),ResultCode.MULTIPART_FILE_EOORO.getMsg());
        }

        String key = TencentCosConfig.COS_IMAGE + "/" + new Date().getTime() +originalFilename.substring(originalFilename.indexOf("."));
        log.info("key = {}", key);

        PutObjectRequest putObjectRequest =
                new PutObjectRequest(tencentCosProperties4Picture.getBucketName(), key, localFile);
        //设置存储类型 默认标准型
        putObjectRequest.setStorageClass(StorageClass.Standard);

        COSClient cosClient = tencentCosConfig.getCoSClient4Picture();

        try {
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //putObjectResult 会返回etag
            String etag = putObjectResult.getETag();
            log.info("eTag = {}", etag);
        } catch (CosServiceException e) {
            log.error("CosServiceException ={}", e.getMessage());
            throw new CosServiceException(e.getMessage());
        } catch (CosClientException e) {
            log.error("CosClientException ={}", e.getMessage());
            throw new CosClientException(e.getMessage());
        }
        cosClient.shutdown();
        String url = tencentCosProperties4Picture.getBaseUrl()+ "/" + key;
        return Result.ok(url);

    }

}
